package com.vvv.designpattern.synchronizedpattern;

/**
 * @author vvv
 * @date 2023-10-15 12 33
 * discription
 */
public class GuardedSuspension {
    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        new Thread(() -> {
            System.out.println("t1 等待结果");
            Object o = guardedObject.get();
            System.out.println("t1" + o);
        }, "t1").start();
        new Thread(() -> {
            System.out.println("t2 开始下载");
            try {
                // 模拟下载
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("t2 下载完成");
            guardedObject.complete("下载结果");
        }, "t2").start();
    }
}


class GuardedObject {
    private Object response;

    public Object get() {
        synchronized (this) {
            while (response == null) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            return response;
        }
    }

    public void complete(Object response) {
        synchronized (this) {
            this.response = response;
            this.notifyAll();
        }
    }

    @Override
    public String toString() {
        return "GuardedObject{" +
                "response=" + response +
                '}';
    }
}

